﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace TidyBlog.Util
{
    /// <summary>
    /// 验证器
    /// </summary>
    public class Validator
    {
        /// <summary>
        /// 匹配IP的正则表达式
        /// </summary>
        public static readonly Regex IP = new Regex(@"\d+(?:\.\d+){3}", RegexOptions.Compiled);
        /// <summary>
        /// 匹配Email的正则表达式
        /// </summary>
        public static readonly Regex Email = new Regex(@"^([.a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]+)*)\.[a-zA-Z]+$", RegexOptions.Compiled);
        /// <summary>
        /// 匹配以http(s)开头的字符串
        /// </summary>
        public static readonly Regex BeginWithHttp = new Regex(@"^https?://", RegexOptions.IgnoreCase);


        /// <summary>
        /// 检查字符串值是否IP
        /// </summary>
        /// <param name="val">字符串</param>
        /// <returns>字符串值是否IP</returns>
        public static bool IsIP(string val)
        {
            if (!IP.IsMatch(val))
            {
                return false;
            }

            string[] sections = val.Split(new[] { '.' });
            byte temp;
            foreach (string i in sections)
            {
                if (!byte.TryParse(i, out temp))
                {
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// 检查字符串是否Email
        /// </summary>
        /// <param name="val">字符串</param>
        /// <returns>字符串是否Email</returns>
        public static bool IsEmail(string val)
        {
            return Email.IsMatch(val);
        }

        /// <summary>
        /// 检查字符串是否QQ号
        /// </summary>
        /// <param name="val">字符串</param>
        /// <returns>字符串是否QQ号</returns>
        public static bool IsQQ(string val)
        {
            return Regex.IsMatch(val, @"^\d{5,}$");
        }

        /// <summary>
        /// 检查字符串是否由逗号隔开的数字
        /// </summary>
        /// <param name="val">字符串</param>
        /// <returns>字符串是否由逗号隔开的数字</returns>
        public static bool IsNumbers(string val)
        {
            return Regex.IsMatch(val, @"\d+(?:,\d+)*");
        }

        /// <summary>
        /// 修复URL格式
        /// </summary>
        /// <param name="url">URL</param>
        /// <returns>修复后的URL</returns>
        public static string fixUrl(string url)
        {
            return BeginWithHttp.IsMatch(url) ? url : "http://" + url;
        }
    }
}